package com.platform.system.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import com.platform.common.exception.BadRequestException;
import com.platform.common.utils.PageUtil;
import com.platform.logging.annotation.Log;
import com.platform.system.system.model.Company;
import com.platform.system.system.model.dto.CompanyDto;
import com.platform.system.system.model.dto.CompanyQueryParam;
import com.platform.system.system.service.CompanyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
* @author Zheng Jie
* @date 2019-03-25
*/
@RestController
@RequiredArgsConstructor
@Api(tags = "系统：公司管理")
@RequestMapping("/api/company")
public class CompanyController {

    private final CompanyService companyService;
    private static final String ENTITY_NAME = "company";

    @ApiOperation("导出公司数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('company:list')")
    public void download(HttpServletResponse response, CompanyQueryParam criteria) throws Exception {
        companyService.download(companyService.queryAll(criteria, false), response);
    }

    @ApiOperation("查询公司")
    @GetMapping
    @PreAuthorize("@el.check('user:list','company:list')")
    public ResponseEntity<Object> query(CompanyQueryParam criteria) throws Exception {
        List<CompanyDto> companyDtos = companyService.queryAll(criteria, true);
        return new ResponseEntity<>(PageUtil.toPage(companyDtos, companyDtos.size()),HttpStatus.OK);
    }

    @ApiOperation("查询公司:根据ID获取同级与上级数据")
    @PostMapping("/superior")
    @PreAuthorize("@el.check('user:list','company:list')")
    public ResponseEntity<Object> getSuperior(@RequestBody List<Long> ids) {
        Set<CompanyDto> companyDtos  = new LinkedHashSet<>();
        for (Long id : ids) {
            CompanyDto companyDto = companyService.findById(id);
            List<CompanyDto> companys = companyService.getSuperior(companyDto, new ArrayList<>());
            companyDtos.addAll(companys);
        }
        return new ResponseEntity<>(companyService.buildTree(new ArrayList<>(companyDtos)),HttpStatus.OK);
    }

    @Log("新增公司")
    @ApiOperation("新增公司")
    @PostMapping
    @PreAuthorize("@el.check('company:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Company resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        companyService.insert(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("修改公司")
    @ApiOperation("修改公司")
    @PutMapping
    @PreAuthorize("@el.check('company:edit')")
    public ResponseEntity<Object> update(@Validated(Company.Update.class) @RequestBody Company resources){
        companyService.modifyById(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除公司")
    @ApiOperation("删除公司")
    @DeleteMapping
    @PreAuthorize("@el.check('company:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){
        Set<Long> companyIds = new HashSet<>();
        for (Long id : ids) {
            List<Company> companyList = companyService.findByPid(id);
            companyIds.add(companyService.findById(id).getId());
            if(CollectionUtil.isNotEmpty(companyList)){
                companyIds = companyService.getDeleteCompanys(companyList, companyIds);
            }
        }
        // 验证是否被部门或用户关联
        companyService.verification(companyIds);
        companyService.deleteByIds(companyIds);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
